﻿@{
    ViewData["Title"] = "简效自疗问诊卡";
}

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>简效自疗在线问诊卡</title>
    <style>
        /* 基本样式 */
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 0;
            background-color: #f7f7f7;
            color: #333;
        }

        h1, h2 {
            text-align: center;
            color: #2c3e50;
        }

        form {
            max-width: 900px;
            margin: 20px auto;
            padding: 20px;
            background: #fff;
            border-radius: 10px;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
        }

        label {
            display: block;
            margin-bottom: 10px;
            font-weight: bold;
        }

        input, textarea, select, button {
            width: 100%;
            padding: 10px;
            margin-bottom: 20px;
            border: 1px solid #ccc;
            border-radius: 5px;
            font-size: 16px;
        }

        textarea {
            resize: vertical;
        }

        button {
            background-color: #3498db;
            color: white;
            border: none;
            cursor: pointer;
        }

            button:hover {
                background-color: #2980b9;
            }

        .tabs {
            display: flex;
            justify-content: center;
            margin-top: 20px;
            background: #3498db;
            border-radius: 10px;
            padding: 10px;
        }

        .tab {
            padding: 10px 20px;
            color: white;
            font-weight: bold;
            cursor: pointer;
            transition: background 0.3s;
        }

            .tab:hover, .tab.active {
                background: #2980b9;
                border-radius: 5px;
            }

        .tab-content {
            display: none;
            max-width: 900px;
            margin: 20px auto;
            padding: 20px;
            background: #fff;
            border-radius: 10px;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
        }

            .tab-content.active {
                display: block;
            }
       
      
    </style>
</head>
<body>
    <h1>简效自疗在线问诊卡</h1>
    <div class="tabs">
        <div class="tab active" data-tab="diagnosis">问诊卡填写</div>
        <div class="tab" data-tab="pulse">脉诊卡填写</div>
    </div>
    <form id="diagnosisForm">
        <div id="diagnosis" class="tab-content active">
            <h2>基本信息</h2>
            <label for="name">姓名</label>
            <input type="text" id="name" name="name" required>

            <label for="gender">性别</label>
            <select id="gender" name="gender" required>
                <option value="男">男</option>
                <option value="女">女</option>
            </select>
            <label for="birthDate">出生年月日(农历)</label>
            <input type="text" id="birthDate" name="birthDate"     placeholder="例：1990-01-15">
            <label for="sickDate">生病日期(公历)</label>
            <input type="text" id="sickDate" name="sickDate" placeholder="例：1990-01-15">
            <label for="requestTime">求方时间</label>
            <input type="datetime-local" id="requestTime" name="requestTime" placeholder="例：1990-01-15">
           
            <label for="birthPlace">出生地</label>
            <input type="text" id="birthPlace" name="birthPlace">

            <label for="currentLocation">现所在地</label>
            <input type="text" id="currentLocation" name="currentLocation">

            <label for="height">身高(cm)</label>
            <input type="number" id="height" name="height" step="0.1">

            <label for="weight">体重(kg)</label>
            <input type="number" id="weight" name="weight" step="0.1">

            <h2>问诊信息</h2>
            <label for="generalSymptoms">全身不舒服的症状</label>
            <textarea id="generalSymptoms" name="generalSymptoms"></textarea>

            <label for="currentSymptoms">目前最不舒服的症状</label>
            <textarea id="currentSymptoms" name="currentSymptoms"></textarea>

            <label for="appetite">胃口如何/酸胀痛或其他情况</label>
            <input type="text" id="appetite" name="appetite">

            <label for="morningFeeling">晨起口中感觉如何</label>
            <input type="text" id="morningFeeling" name="morningFeeling">

            <label for="coldSensitivity">吃凉东西是否容易拉肚子</label>
            <select id="coldSensitivity" name="coldSensitivity">
                <option value="是">是</option>
                <option value="否">否</option>
            </select>

            <label for="sleepDetails">睡眠情况</label>
            <textarea id="sleepDetails" name="sleepDetails"></textarea>

            <label for="stoolDetails">大便情况</label>
            <textarea id="stoolDetails" name="stoolDetails"></textarea>

            <label for="urineDetails">小便情况</label>
            <textarea id="urineDetails" name="urineDetails"></textarea>

            <label for="tongueImageFront">舌头正面照含完整面部</label>
            <input type="file" id="tongueImageFront" name="tongueImageFront" accept="image/*">

            <label for="tongueImageBack">舌底照片</label>
            <input type="file" id="tongueImageBack" name="tongueImageBack" accept="image/*">

            <label for="bloodPressure">最近血压高低</label>
            <input type="text" id="bloodPressure" name="bloodPressure">

            <label for="emotions">平时性情、脾气? 最近情绪如何</label>
            <textarea id="emotions" name="emotions"></textarea>

            <label for="temperatureSensitivity">手足冷/手足热</label>
            <select id="temperatureSensitivity" name="temperatureSensitivity">
                <option value="怕冷">手足都冷</option>
                <option value="怕热">手足都热</option>
                <option value="怕热">手热足冷</option>
               <option value="怕热">指尖冷</option>
                <option value="正常">冬天冷夏天热</option>
            </select>

            <label for="menstrualStatus">女是否痛经/男是否经常滑精</label>
            <textarea id="menstrualStatus" name="menstrualStatus"></textarea>        
            <label for="waterPreference">内心想喝热水、凉水或不喜欢喝水</label>
            <select id="waterPreference" name="waterPreference">
                <option value="热水">热水</option>
                <option value="凉水">凉水</option>
                <option value="不喜欢喝水">不喜欢喝水</option>
            </select>
            <label for="medicalHistory">重要病史、发病诱因（是否做过手术）</label>
            <textarea id="medicalHistory" name="medicalHistory"></textarea>
        </div>
        <!-- 脉诊卡填写 -->
    
        <div id="pulse" class="tab-content">
            <h2>脉诊卡填写</h2>
            <a href="https://www.bilibili.com/video/BV1XDGSzyEbp/?vd_source=c5d62cb47e969d2d3f19a07f223574b5" // 请替换为实际视频链接
               target="_blank"
               style="font-size: 14px; color: #0066cc; text-decoration: none;"
               onmouseover="this.style.textDecoration='underline'"
               onmouseout="this.style.textDecoration='none'">
                📽 自己把脉教学短视频
            </a>
            <table border="1" style="border-collapse: collapse; width: 100%; text-align: center;">
                <thead>
                    <tr style="border: 1px solid black;">
                        <th style="border: 1px solid black;">部位</th>
                        <th>浮</th>
                        <th>中</th>
                        <th>沉</th>
                    </tr>
                </thead>
                <tbody>
                    <tr style="border: 1px solid black;">
                        <td style="border: 1px solid black;">左寸</td>
                        <td>
                            <select id="leftCunFloat" name="leftCunFloat">
                                <option value="0">无</option>
                                <option value="5">弱</option>
                                <option value="10">有</option>
                                <option value="20">有力</option>
                                <option value="30">很有力</option>
                                <option value="40">非常顶</option>
                            </select>
                        </td>
                        <td>
                            <select id="leftCunMiddle" name="leftCunMiddle">
                                <option value="0">无</option>
                                <option value="5">弱</option>
                                <option value="10">有</option>
                                <option value="20">有力</option>
                                <option value="30">很有力</option>
                                <option value="40">非常顶</option>
                            </select>
                        </td>
                        <td>
                            <select id="leftCunDeep" name="leftCunDeep">
                                <option value="0">无</option>
                                <option value="5">弱</option>
                                <option value="10">有</option>
                                <option value="20">有力</option>
                                <option value="30">很有力</option>
                                <option value="40">非常顶</option>
                            </select>
                        </td>
                    </tr>
                    <tr style="border: 1px solid black;">
                        <td style="border: 1px solid black;">左关</td>
                        <td>
                            <select id="leftGuanFloat" name="leftGuanFloat">
                                <option value="0">无</option>
                                <option value="5">弱</option>
                                <option value="10">有</option>
                                <option value="20">有力</option>
                                <option value="30">很有力</option>
                                <option value="40">非常顶</option>
                            </select>
                        </td>
                        <td>
                            <select id="leftGuanMiddle" name="leftGuanMiddle">
                                <option value="0">无</option>
                                <option value="5">弱</option>
                                <option value="10">有</option>
                                <option value="20">有力</option>
                                <option value="30">很有力</option>
                                <option value="40">非常顶</option>
                            </select>
                        </td>
                        <td>
                            <select id="leftGuanDeep" name="leftGuanDeep">
                                <option value="0">无</option>
                                <option value="5">弱</option>
                                <option value="10">有</option>
                                <option value="20">有力</option>
                                <option value="30">很有力</option>
                                <option value="40">非常顶</option>
                            </select>
                        </td>
                    </tr>
                    <tr style="border: 1px solid black;">
                        <td style="border: 1px solid black;">左尺</td>
                        <td>
                            <select id="leftChiFloat" name="leftChiFloat">
                                <option value="0">无</option>
                                <option value="5">弱</option>
                                <option value="10">有</option>
                                <option value="20">有力</option>
                                <option value="30">很有力</option>
                                <option value="40">非常顶</option>
                            </select>
                        </td>
                        <td>
                            <select id="leftChiMiddle" name="leftChiMiddle">
                                <option value="0">无</option>
                                <option value="5">弱</option>
                                <option value="10">有</option>
                                <option value="20">有力</option>
                                <option value="30">很有力</option>
                                <option value="40">非常顶</option>
                            </select>
                        </td>
                        <td>
                            <select id="leftChiDeep" name="leftChiDeep">
                                <option value="0">无</option>
                                <option value="5">弱</option>
                                <option value="10">有</option>
                                <option value="20">有力</option>
                                <option value="30">很有力</option>
                                <option value="40">非常顶</option>
                            </select>
                        </td>
                    </tr>
                    <tr style="border: 1px solid black;">
                        <td style="border: 1px solid black;">右寸</td>
                        <td>
                            <select id="rightCunFloat" name="rightCunFloat" style="width: 100%; padding: 5px;">
                                <option value="0">无</option>
                                <option value="5">弱</option>
                                <option value="10">有</option>
                                <option value="20">有力</option>
                                <option value="30">很有力</option>
                                <option value="40">非常顶</option>
                            </select>
                        </td>
                        <td>
                            <select id="rightCunMiddle" name="rightCunMiddle" style="width: 100%; padding: 5px;">
                                <option value="0">无</option>
                                <option value="5">弱</option>
                                <option value="10">有</option>
                                <option value="20">有力</option>
                                <option value="30">很有力</option>
                                <option value="40">非常顶</option>
                            </select>
                        </td>
                        <td>
                            <select id="rightCunDeep" name="rightCunDeep" style="width: 100%; padding: 5px;">
                                <option value="0">无</option>
                                <option value="5">弱</option>
                                <option value="10">有</option>
                                <option value="20">有力</option>
                                <option value="30">很有力</option>
                                <option value="40">非常顶</option>
                            </select>
                        </td>
                    </tr>
                    <tr style="border: 1px solid black;">
                        <td style="border: 1px solid black;">右关</td>
                        <td>
                            <select id="rightGuanFloat" name="rightGuanFloat" style="width: 100%; padding: 5px;">
                                <option value="0">无</option>
                                <option value="5">弱</option>
                                <option value="10">有</option>
                                <option value="20">有力</option>
                                <option value="30">很有力</option>
                                <option value="40">非常顶</option>
                            </select>
                        </td>
                        <td>
                            <select id="rightGuanMiddle" name="rightGuanMiddle" style="width: 100%; padding: 5px;">
                                <option value="0">无</option>
                                <option value="5">弱</option>
                                <option value="10">有</option>
                                <option value="20">有力</option>
                                <option value="30">很有力</option>
                                <option value="40">非常顶</option>
                            </select>
                        </td>
                        <td>
                            <select id="rightGuanDeep" name="rightGuanDeep" style="width: 100%; padding: 5px;">
                                <option value="0">无</option>
                                <option value="5">弱</option>
                                <option value="10">有</option>
                                <option value="20">有力</option>
                                <option value="30">很有力</option>
                                <option value="40">非常顶</option>
                            </select>
                        </td>
                    </tr>
                    <tr style="border: 1px solid black;">
                        <td style="border: 1px solid black;">右尺</td>
                        <td>
                            <select id="rightChiFloat" name="rightChiFloat" style="width: 100%; padding: 5px;">
                                <option value="0">无</option>
                                <option value="5">弱</option>
                                <option value="10">有</option>
                                <option value="20">有力</option>
                                <option value="30">很有力</option>
                                <option value="40">非常顶</option>
                            </select>
                        </td>
                        <td>
                            <select id="rightChiMiddle" name="rightChiMiddle" style="width: 100%; padding: 5px;">
                                <option value="0">无</option>
                                <option value="5">弱</option>
                                <option value="10">有</option>
                                <option value="20">有力</option>
                                <option value="30">很有力</option>
                                <option value="40">非常顶</option>
                            </select>
                        </td>
                        <td>
                            <select id="rightChiDeep" name="rightChiDeep" style="width: 100%; padding: 5px;">
                                <option value="0">无</option>
                                <option value="5">弱</option>
                                <option value="10">有</option>
                                <option value="20">有力</option>
                                <option value="30">很有力</option>
                                <option value="40">非常顶</option>
                            </select>
                        </td>
                    </tr>
                </tbody>
            </table>

          @*   <label for="pulseSummary" style="margin-top: 20px; display: block;">脉总体情况</label> *@
          @*   <div id="pulseSummary" style="margin-top: 10px;">
                <label><input type="checkbox" class="pulse-checkbox" name="pulseSummary" value="变脉"> 变脉（脉跳不流利；时大时小；时快时慢；跳跳停停）</label><br>
                <label><input type="checkbox" class="pulse-checkbox" name="pulseSummary" value="尺脉不平衡"> 尺脉不平衡</label><br>
                <label><input type="checkbox" class="pulse-checkbox" name="pulseSummary" value="弦细数"> 弦细数</label><br>
                <label><input type="checkbox" class="pulse-checkbox" name="pulseSummary" value="迟脉"> 迟脉</label><br>
                <label><input type="checkbox" class="pulse-checkbox" name="pulseSummary" value="浮洪大"> 浮洪大</label>
            </div> *@

            <label for="pulseSummary" style="margin-top: 20px; display: block; font-weight: bold;">脉总体情况</label>
            <div id="pulseSummary" style="margin-top: 10px; border: 1px solid #ccc; padding: 10px; border-radius: 5px;">
                <div style="margin-bottom: 8px; display: flex; align-items: center; border: 1px solid #ccc; padding: 5px; border-radius: 3px;">
                    <label style="display: flex; align-items: center; width: 100%;">
                        <span style="width: 100%;">变脉（脉跳不流利；时大时小；时快时慢；跳跳停停）</span>
                    </label>
                    <input type="checkbox" class="pulse-checkbox" name="pulseSummary" value="变脉" style="width: 50px;margin-right: 5px; border: 1px solid #ccc; padding: 3px; border-radius: 3px;">
                     
                </div>
                <div style="margin-bottom: 8px; display: flex; align-items: center; border: 1px solid #ccc; padding: 5px; border-radius: 3px;">
                    <label style="display: flex; align-items: center; width: 100%;">
                        <span style="width: 100%;">尺脉不平衡</span>
                        <input type="checkbox" class="pulse-checkbox" name="pulseSummary" value="尺脉不平衡" style="width: 50px;margin-right: 5px; border: 1px solid #ccc; padding: 3px; border-radius: 3px;">
                        
                    </label>
                </div>
                <div style="margin-bottom: 8px; display: flex; align-items: center; border: 1px solid #ccc; padding: 5px; border-radius: 3px;">
                    <label style="display: flex; align-items: center; width: 100%;">
                        <span style="width: 100%;">弦细数</span>
                        <input type="checkbox" class="pulse-checkbox" name="pulseSummary" value="弦细数" style="width: 50px;margin-right: 5px; border: 1px solid #ccc; padding: 3px; border-radius: 3px;">
                        
                    </label>
                </div>
                <div style="margin-bottom: 8px; display: flex; align-items: center; border: 1px solid #ccc; padding: 5px; border-radius: 3px;">
                    <label style="display: flex; align-items: center; width: 100%;">
                        <span style="width: 100%;">迟脉</span>
                        <input type="checkbox" class="pulse-checkbox" name="pulseSummary" value="迟脉" style="width: 50px;margin-right: 5px; border: 1px solid #ccc; padding: 3px; border-radius: 3px;">
                       
                    </label>
                </div>
                <div style="display: flex; align-items: center; border: 1px solid #ccc; padding: 5px; border-radius: 3px;">
                    <label style="display: flex; align-items: center; width: 100%;">
                        <span style="width: 100%;">浮洪大</span>
                        <input type="checkbox" class="pulse-checkbox" name="pulseSummary" value="浮洪大" style="width: 50px;margin-right: 5px; border: 1px solid #ccc; padding: 3px; border-radius: 3px;">
                      
                    </label>
                </div>
            </div>


        </div>

        <button type="submit">提交</button>
    </form>

    <script>
        // Tab切换功能
        const tabs = document.querySelectorAll('.tab');
        const tabContents = document.querySelectorAll('.tab-content');

        tabs.forEach(tab => {
            tab.addEventListener('click', () => {
                // 移除所有tab和内容的active状态
                tabs.forEach(t => t.classList.remove('active'));
                tabContents.forEach(tc => tc.classList.remove('active'));

                // 为当前点击的tab及其对应的内容添加active状态
                tab.classList.add('active');
                const tabId = tab.getAttribute('data-tab');
                document.getElementById(tabId).classList.add('active');
            });
        });

        document.getElementById('diagnosisForm').addEventListener('submit', async (e) => {
            e.preventDefault();

            // 获取表单数据
            const formData = new FormData(e.target);
            const jsonData = Object.fromEntries(formData.entries());

            // 随机生成 StudentID
            jsonData.StudentID = `SID${Date.now()}${Math.floor(Math.random() * 10000)}`;

            // 上传图片并获取上传结果
            const imageData = await uploadImages();

            if (imageData) {
                // 将上传的图片路径添加到 JSON 数据中
                if (imageData.TongueImageFront) {
                    jsonData.TongueImageFront = imageData.TongueImageFront;
                }
                if (imageData.TongueImageBack) {
                    jsonData.TongueImageBack = imageData.TongueImageBack;
                }
            }

            // 处理 pulseSummary 的多选值
            const selectedPulseSummaries = Array.from(document.querySelectorAll('.pulse-checkbox:checked'))
                .map(checkbox => checkbox.value)
                .join(',');

            // 如果有选择的值，则添加到 jsonData 中
            if (selectedPulseSummaries) {
                jsonData.pulseSummary = selectedPulseSummaries;
            } else {
                delete jsonData.pulseSummary; // 如果没有选择任何值，删除该字段
            }
            // 清理空值字段
            for (const key in jsonData) {
                if (!jsonData[key] || (typeof jsonData[key] === 'object' && Object.keys(jsonData[key]).length === 0)) {
                    delete jsonData[key];
                }
            }
            // console.log("提交的 JSON 数据:", JSON.stringify(jsonData));

            try {
                const response = await fetch('/api/diagnosis/add-diagnosis', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json', // 确保 Content-Type 为 application/json
                    },
                    body: JSON.stringify(jsonData), // 发送 JSON 数据
                });

                if (!response.ok) {
                    const result = await response.json();
                    throw new Error(result.message || '提交失败');
                }

                // 跳转至详情页面
                const queryString = `studentID=${jsonData.StudentID}`;
                window.location.href = `/api/diagnosis/Details?${queryString}`;
            } catch (error) {
                console.error('提交失败:', error.message, error);
                alert(`提交失败: ${error.message}`);
            }
        });
async function uploadImages() {
    const tongueFrontImageInput = document.getElementById('tongueImageFront');
    const tongueBackImageInput = document.getElementById('tongueImageBack');
    const validTypes = ['image/jpeg', 'image/png', 'image/jpg'];
    const maxSize = 5 * 1024 * 1024;
    const imageData = new FormData();

    // 压缩并处理图片的通用函数
    async function processImage(file, fieldName) {
        if (!validTypes.includes(file.type)) {
            alert(`文件类型不允许，仅支持 jpg, jpeg, png 格式`);
            return null;
        }

        try {
            const compressedFile = await compressImage(file);
            if (compressedFile.size > maxSize) {
                alert('压缩后图片大小仍超过5MB');
                return null;
            }
            imageData.append(fieldName, compressedFile, file.name);
            return true;
        } catch (error) {
            console.error('图片处理失败:', error);
            alert(`图片处理失败: ${error.message}`);
            return null;
        }
    }

    // 处理正面图片
    let hasFiles = false;
    if (tongueFrontImageInput.files.length > 0) {
        const result = await processImage(
            tongueFrontImageInput.files[0], 
            'TongueImageFront'
        );
        if (result) hasFiles = true;
    }

    // 处理背面图片
    if (tongueBackImageInput.files.length > 0) {
        const result = await processImage(
            tongueBackImageInput.files[0],
            'TongueImageBack'
        );
        if (result) hasFiles = true;
    }

    if (!hasFiles) {
        alert("请上传正面或反面照片");
        return;
    }

    try {
        const response = await fetch('/api/diagnosis/upload-tongue-images', {
            method: 'POST',
            body: imageData
        });

        if (!response.ok) {
            const errorData = await response.json();
            throw new Error(errorData.message || '图片上传失败');
        }

        const responseData = await response.json();
        console.log('上传成功', responseData);
        return responseData;
    } catch (error) {
        console.error('上传失败:', error);
        alert(`上传失败: ${error.message}`);
    }
}

// 图片压缩函数
function compressImage(file, quality = 0.7, maxWidth = 800) {
    return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.onload = (e) => {
            const img = new Image();
            img.onload = () => {
                // 计算缩放尺寸
                let width = img.width;
                let height = img.height;
                if (width > maxWidth) {
                    height = Math.round((height * maxWidth) / width);
                    width = maxWidth;
                }

                // 创建Canvas
                const canvas = document.createElement('canvas');
                canvas.width = width;
                canvas.height = height;

                // 绘制图片
                const ctx = canvas.getContext('2d');
                ctx.drawImage(img, 0, 0, width, height);

                // 转换为JPEG格式
                canvas.toBlob(
                    (blob) => {
                        if (!blob) {
                            reject(new Error('图片压缩失败'));
                            return;
                        }
                        resolve(
                            new File([blob], file.name, {
                                type: 'image/jpeg',
                                lastModified: Date.now()
                            })
                        );
                    },
                    'image/jpeg',
                    quality
                );
            };
            img.onerror = () => reject(new Error('图片加载失败'));
            img.src = e.target.result;
        };
        reader.onerror = (error) => reject(error);
        reader.readAsDataURL(file);
    });
}
    </script>

</body>
</html>
